<script setup lang="ts">
import {DictType, OpenFormType, Perm} from "@/utils/enum-type";
import {RuleInfoType} from "@/api/sys/admin/rule-info/types";
import {useGetOptions} from "@/utils/use/use-get-options";
import {cloneDeep, initPageQuery} from "@/utils/common-fn";
import {
  addRuleInfoApi,
  deleteRuleInfoApi,
  editRuleInfoApi,
  getRuleInfoByIdApi,
  getRuleInfoListApi
} from "@/api/sys/admin/rule-info";
import {openConfirm} from "@/components/MyComponent/XMessageBox";
import {FormInstance, FormRules} from "element-plus";
import {Ref} from "vue";

/**
 * 公共字段
 */
const title = '规则说明'
const loading = ref(false)

/**
 * table
 */
    // table数据
let tableData: Ref<RuleInfoType[]> = ref([])
// 获取options
let allOptions = useGetOptions(DictType.Status, DictType.RuleInfoType);
const statusOptions = computed(() => allOptions.value[0])
const ruleInfoTypeOptions = computed(() => allOptions.value[1])
/**
 * 搜索和分页
 */
// 总数
const total = ref(0)
// 搜索ref
const searchRef = ref<FormInstance>()
// 分页信息,以及查询条件,用于发送api
const queryData = reactive(initPageQuery<RuleInfoType>({order: {sort: 'asc'}}))

/**
 * 表单
 */
    // 弹出框可见
const visible = ref(false)
// 最好初始化表单类型
const initForm: RuleInfoType = {id: -1, title: '', type: 1, status: 1, sort: 1}
// 表单数据
const formData: Ref<RuleInfoType> = ref(cloneDeep(initForm))
// 打开表单类型
let openFormType: Ref<OpenFormType> = ref(OpenFormType.Add)
// 打开表单的文字
const addOrEditWord = openFormType.value === OpenFormType.Add ? '添加' : '修改'
// 编辑表单时规则验证
const ruleFormRef = ref<FormInstance>()
// 规则:适用于添加和修改
const rules: FormRules<RuleInfoType> = {
  title: [{required: true, message: '请输入标题', trigger: 'blur'}],
}

/**
 * --------方法相关-----------
 */
// 设置编辑对话框可见
function setVisible(bolValue: boolean) {
  visible.value = bolValue
}

// 获取列表
async function getList() {
  [tableData.value, total.value] = await getRuleInfoListApi(queryData);
  allOptions = useGetOptions(DictType.Status, DictType.RuleInfoType);
}

// 打开表单
function open(): void // 打开添加
async function open(id: number): Promise<void> // 打开修改
async function open(id?: number) {
  if (id) {
    // 编辑
    formData.value = await getRuleInfoByIdApi(id)
    openFormType.value = OpenFormType.Edit
  } else {
    // 新增
    formData.value = cloneDeep(initForm)
    openFormType.value = OpenFormType.Add
  }
  setVisible(true)
}

// 重置搜索
async function resetSearch(formEl: FormInstance | undefined) {
  if (!formEl) {
    return;
  }
  formEl.resetFields()
  queryData.query = {}
  await nextTick()
  await getList()
}

// 表格排序
async function sortTable({prop, order}: {
  prop: string,
  order: 'descending' | 'ascending' | null
}) {
  if (order === 'descending' || !order) {
    queryData.order = {[prop]: 'desc'}
  } else {
    queryData.order = {[prop]: 'asc'}
  }
  await getList()
}


// 点击删除
async function openDelete(id: number) {
  if (await openConfirm('确定删除' + title)) {
    await deleteRuleInfoApi(id)
    ElMessage.success('删除成功')
    await getList()
  }
}

// 提交新增/编辑
async function submit(formEl: FormInstance | undefined) {
  if (!formEl) {
    return;
  }
  await formEl.validate((valid, fields) => {
    if (valid) {
      let promise: Promise<any>
      if (openFormType.value === OpenFormType.Add) {
        promise = addRuleInfoApi(formData.value)
      } else {
        promise = editRuleInfoApi(formData.value.id, formData.value)
      }
      promise.then(async () => {
        loading.value = true
        await getList()
        ElMessage.success(`${addOrEditWord}成功`)
        setVisible(false)
      }).finally(() => {
        loading.value = false
      })
    } else {
      console.log('错误的字段', fields)
    }
  })
}

watch([() => queryData.pageSize, () => queryData.currentPage], async () => {
  await getList()
})
// 载入查询
onMounted(async () => {
  await getList()
})
</script>

<template>
  <!--  查询 -->
  <x-card>
    <el-form :inline="true" :model="queryData.query" label-suffix=":" ref="searchRef" class="flex flex-items-center">
      <el-form-item label="标题" prop="name">
        <el-input v-model="queryData.query.title" clearable/>
      </el-form-item>
      <el-form-item label="类型" prop="type">
        <x-dict-select v-model="queryData.query.type" type-code="rule_info_type" type="select"/>
      </el-form-item>
      <el-form-item label="状态" prop="status">
        <x-dict-select v-model="queryData.query.status" type-code="status" type="select"/>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="getList()">查询</el-button>
      </el-form-item>
      <el-form-item>
        <el-button @click="resetSearch(searchRef)" circle>
          <i-ep-refresh-left/>
        </el-button>
      </el-form-item>
    </el-form>
  </x-card>
  <!-- 按钮 -->
  <x-card>
    <div class="flex">
      <div v-perm="[Perm.SysRuleInfoAdd]" class="mr-1em">
        <!--    新增按钮-->
        <el-button type="success" @click="open()">
          <i-ep-plus/>
          <span>新增</span>
        </el-button>
      </div>
    </div>
  </x-card>
  <!--  表格-->
  <x-card>
    <el-table :data="tableData" style="width: 100%" show-overflow-tooltip @sort-change="sortTable" stripe>
      <el-table-column prop="title" label="标题" min-width="100" sortable="custom" fixed/>
      <el-table-column prop="remark" label="描述" min-width="500" :show-overflow-tooltip="false">
        <template #default="{row}">
          <el-input type="textarea" autosize readonly :model-value="row.remark"/>
        </template>
      </el-table-column>
      <el-table-column prop="sort" label="排序" min-width="50" align="center"/>
      <el-table-column prop="type" sortable="custom" label="类型" width="80">
        <template #default="{row}">
          <x-tag :value="row.type" :options="ruleInfoTypeOptions"/>
        </template>
      </el-table-column>
      <el-table-column prop="status" label="状态" width="80">
        <template #default="{row}">
          <x-tag :value="row.status" :options="statusOptions"/>
        </template>
      </el-table-column>
      <el-table-column
          v-perm="[[Perm.SysRuleInfoDelete],[Perm.SysRuleInfoEdit]]"
          fixed="right" label="操作" width="200">
        <template #default="{row}">
          <el-button v-perm="Perm.SysRuleInfoEdit" link type="primary" size="small" @click="open(row.id)">
            <i-ep-edit/>
            <span>编辑</span>
          </el-button>
          <el-button v-perm="Perm.SysRuleInfoDelete" link type="danger" size="small" @click="openDelete(row.id)">
            <i-ep-delete/>
            <span>删除</span>
          </el-button>
        </template>
      </el-table-column>
    </el-table>
  </x-card>
  <!--  分页-->
  <x-card>
    <XPagination
        v-model:page-size="queryData.pageSize"
        v-model:current-page="queryData.currentPage"
        v-model:total="total"
    />
  </x-card>
  <!-- 添加对话框:添加 -->
  <el-dialog draggable v-model="visible" :title="`${addOrEditWord}${title}`" width="600" destroy-on-close>
    <el-form :model="formData" label-suffix=":" label-width="100" ref="ruleFormRef" :rules="rules">
      <el-form-item label="标题" prop="title">
        <el-input v-model="formData.title"/>
      </el-form-item>
      <el-form-item label="类型" prop="type">
        <x-dict-select type-code="rule_info_type" v-model="formData.type" type="select"/>
      </el-form-item>
      <el-form-item label="描述" prop="remark">
        <el-input type="textarea" autosize v-model="formData.remark"/>
      </el-form-item>
      <el-form-item label="排序" prop="sort">
        <el-input-number v-model="formData.sort"/>
      </el-form-item>
      <el-form-item label="状态">
        <x-dict-select type-code="status" v-model="formData.status"/>
      </el-form-item>
    </el-form>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="setVisible(false)">取消</el-button>
        <el-button type="primary" :loading="loading" @click="submit(ruleFormRef)">
          确定
        </el-button>
      </span>
    </template>
  </el-dialog>
</template>

<style scoped lang="scss">

</style>